//
//  YYGNoteManager.swift
//  FastV
//
//  Created by DC on 2024/6/25.
//

import Foundation

// MARK: -- 文件处理模型
class YYGNoteManager: NSObject {
    static let shared = YYGNoteManager()
    private override init() {}
    
    //类型
    private let YYG_NoteFile = "YYGNote"
    
    //获取路径
    private func getPath(path: String)-> String {
        var filepath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        filepath+="/\(YYG_NoteFile).plist"
        return filepath
    }
    
    //存储数据
    private func saveArray(path: String, _ data: [[String: Any]]){
             let filePath = getPath(path: path)
             NSKeyedArchiver.archiveRootObject(data, toFile: filePath)
        }
   //  获取数据
    private func getAarray(path: String)->[[String: Any]]{
        let filePath = getPath(path: path)
        guard var array = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? [[String: Any]] else{
            return []
        }
        return array
    }
    // MARK: -- 添加下载产品数据
    func addNote(note: NoteModel){
        guard let dic = note.toJSON() else {
            return
        }
        var array = getAarray(path: YYG_NoteFile)
        array.append(dic)
        saveArray(path: YYG_NoteFile, array)
    }
    
    // MARK: -- 返回数据
    func getNotes()->[NoteModel]{
        
        let array = getAarray(path: YYG_NoteFile)
        guard let lists = JSONDeserializer<NoteModel>.deserializeModelArrayFrom(array: array) as? [NoteModel] else {
            return []
        }
        return lists
    }
    
    // MARK: -- 移除产品数据
    func removeNote(note: NoteModel){
        
        let array = getAarray(path: YYG_NoteFile)
        let arr = array.filter { dic in
            return !(dic.strValue("id") == note.id)
        }
        saveArray(path: YYG_NoteFile, arr)
    }
    
    // MARK: -- 移除所有产品
    func removeAll(){
        saveArray(path: YYG_NoteFile, [])
    }
    
    // MARK: -- 移除沙盒中有些话的具体文件
    func removeItem(fileName: String){
        
        var filePath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        filePath += "/Files/\(fileName)"
        try? FileManager.default.removeItem(atPath: filePath)
    }
   
}
